<?php

class CustomControllerAction extends Zend_Controller_Action {

    public $db;
    public $cache;
    public $configuration;
    public $currency;
    

    public function init() {
        $this->db = Zend_Registry::get('db');
        $this->cache = Zend_Registry::get('cache');
        $this->configuration = DatabaseObject_Config::GetConfig($this->db);
        $this->updateCurrency();
    }

    public function getConfigValue($name) {
        return DatabaseObject_Config::GetConfigValue($this->db, $name);
    }

    public function getUrl($action = null, $controller = null) {
        $url = rtrim($this->getRequest()->getBaseUrl(), '/') . '/';
        $url .= $this->_helper->url->simple($action, $controller);

        return '/' . ltrim($url, '/');
    }
  
    public function preDispatch() {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $this->view->authenticated = true;
            $this->view->identity = $auth->getIdentity();
            // количество новых заявок
            $requestsCount = DatabaseObject_Friends::GetRequestsCount($this->db, $auth->getIdentity()->id);
            $this->view->requestsCount = $requestsCount;
            // количество новых сообщений
            $newMessagesCount = DatabaseObject_Pm::GetUnreadCount($this->db, $auth->getIdentity()->id);
            $this->view->newPmCount = $newMessagesCount;
            // подсчет корзины 
            $cart = DatabaseObject_Basket::GetCart($this->db, $auth->getIdentity()->id, 'cart');
            $this->view->minicart = $cart;
            // валюта сайта
            $c = DatabaseObject_User::GetCurrencyUser($this->db, $auth->getIdentity()->id);
            $this->view->nomail =  DatabaseObject_User::IsApprovedMail($this->db, Zend_Auth::getInstance()->getIdentity()->login);
                   
            $_SESSION['currency'] = Zend_Registry::get('db')->fetchOne("SELECT name FROM currency WHERE id='$c'");
        } else {
            $this->view->authenticated = false;
            // миникорзина гостя
            $cart = CustomControllerAction::getCart();
            $this->view->minicart = $cart;
            // валюта сайто по умолчанию
            $_SESSION['currency'] = 'грн';
        }
        // валюта сайта
      
        $this->view->currency = $_SESSION['currency'];
    }

    public function postDispatch() {
        $this->view->isXmlHttpRequest = $this->getRequest()->isXmlHttpRequest();

        $this->view->config = Zend_Registry::get('config');
    }

    // запись в логи
    public function writeLog($note) {
        DatabaseObject_Logger::WriteLog($this->db, $note);
    }

    // создание ссылки
    public function getCustomUrl($options, $route) {
        return $this->_helper->url->url($options, $route);
    }

    public function sendJSON($data) {
        $this->_helper->viewRenderer->setNoRender();
        $this->getResponse()->setHeader('content-type', 'application/json');

        echo Zend_Json::encode($data);
    }
    // получение данных для миникорзины гостя
    public function getCart($controller = null) {
        if (isset($_SESSION['cart'])){
        $data = $_SESSION['cart'];
        $price = 0;
        $i = 0;
        if ($data)
            foreach ($data as $k => $v) {

                foreach ($v as $kk => $vv) {
                    $product = new DatabaseObject_Products($this->db);
                    $product->load($kk);
                    $price += $product->price * $vv;
                    $i++;
                }
            }
        $cart = array();
        $cart['price'] = $price;
        $cart['count'] = $i;
        unset($product);
       } else
            { 
        $cart = array();
        $cart['price'] = 0;
        $cart['count'] = 0;
            }
             return $cart;
    }
    // функция добавление корзины в базу из сессии (При входе пользователя или регистрации гостя)
    public function SessionFormDb($id, $count = 1) {
        $tmp = DatabaseObject_Basket::GetCountProductBascket($this->db, $id, Zend_Auth::getInstance()->getIdentity()->id, 'cart');

        if ($tmp) {
            $basket = new DatabaseObject_Basket($this->db);
            $basket->load($tmp);
            $basket->count = $basket->count + $count;
            $basket->save();
        } else {
            $basket = new DatabaseObject_Basket($this->db);
            $shop = new DatabaseObject_Products($this->db);
            $shop->load($id);
            $basket->userId = Zend_Auth::getInstance()->getIdentity()->id;
            $basket->shopId = $shop->userId;
            $basket->productId = $id;
            $basket->status = 'cart';
            $basket->count = $count;
            $basket->save();
            unset($basket);
        }
        unset($shop);
    }
    // получение название страны, региона и города пользователя
    public function getCountryCity($country = 0, $city = 0) {

        if ($country != 0) {

            $countrys = Zend_Registry::get('db')->fetchAll("SELECT *  FROM geo_countries WHERE country_id='$country'");
        }
        if ($city != 0) {
            $citys = Zend_Registry::get('db')->fetchAll("SELECT * FROM geo_cities WHERE city_id='$city'");
            $reg = $citys[0]['rid'];
            $region = Zend_Registry::get('db')->fetchAll("SELECT * FROM geo_regions WHERE region_id='$reg'");
        }
        // обращаемся к API и декодируем результат
        if ($country != 0 && $city != 0){
        $found[] = array(
            "city" => array(
                "id" => $citys[0]['city_id'],
                "title" => $citys[0]['city_name'],
            ),
            "country" => array(
                "id" => $countrys[0]['country_id'],
                "title" => $countrys[0]['country_name'],
            ),
            "region" => array(
                "id" => $region[0]['region_id'],
                "title" => $region[0]['region_name'],
            ),
        );
        return $found;
        }
        else
        {return false;}
        
    }

    // междоменный ajax 
    public function getCurl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $translate = curl_exec($ch);
        curl_close($ch);
        $json = json_decode($translate, true);
        return $json;
    }

    // вывод списка стран
    public function getCountry() {
        $country = Zend_Registry::get('db')->fetchAll("SELECT country_name, country_id  FROM geo_countries");

        if ($country) {
            $result = array('country' => $country);
        } else {
            $result = array('type' => 'error');
        }
        return $result;
    }

    //вывод списка регионов определенной страны
    public function getRegion($id) {

        if (!is_numeric($id)) {

            $cou = Zend_Registry::get('db')->fetchOne("SELECT country_id  FROM geo_countries WHERE country_name='$id'");
            $id = $cou;
        }
       
        $regions = Zend_Registry::get('db')->fetchAll("SELECT region_name, region_id  FROM geo_regions WHERE cid='$id'");

        if ($regions) {
            $result = array('regions' => $regions);
        } else {
            $result = array('type' => 'error');
        }
        return $result;
    }

    // вывод городов определеного региона
    public function getCity($id) {

        $region_id = @intval($_GET['region_id']);
        if (!is_numeric($id)) {

            $cou = Zend_Registry::get('db')->fetchOne("SELECT region_id  FROM geo_regions WHERE region_name='$id'");
            $id = $cou;
        }
        $citys = Zend_Registry::get('db')->fetchAll("SELECT city_name, city_id FROM geo_cities WHERE rid='$id'");

        if ($citys) {
            $result = array('citys' => $citys);
        } else {
            $result = array('type' => 'error');
        }
        return $result;
    }
    public function getCityName($id) {

      //  $region_id = $_GET['region_id'];
        if (!is_numeric($id)) {

             $citys = Zend_Registry::get('db')->fetchAll("SELECT city_id as id FROM geo_cities WHERE city_name='$id'");
          // $id = $cou;
        }
        else
        {
        $citys = Zend_Registry::get('db')->fetchAll("SELECT city_id as id FROM geo_cities WHERE cid='$id'");
        }
        
       
        if ($citys) {
           
        foreach ($citys as $v)
            $kkk[] = $v['id'];
        $citys = implode(',', $kkk);
         $result =  $citys;
        } else {
            $result = '';
        }
        return $result;
    }
    // Вывод массива
    public function pre($arr) {
        echo "<pre>";
        print_r($arr);
        echo "</pre>";
    }
    // получение курса валют НБУ
    public function addCurrency($char3) {
        $exchange_url = 'http://bank-ua.com/export/currrate.xml';
        $xml = simplexml_load_file($exchange_url);
       
        if ($xml !== FALSE) {
            // все хорошо, можно работать дальше -
            // в XML-данных нет ошибки

            foreach ($xml->children() as $item) {
                $row = simplexml_load_string($item->asXML());
                
                // Выполняем XPath-запрос к XML-данным
                $v = $row->xpath('//char3[. ="' . $char3 . '"]');

                if ($v) {
                    $result = $item;
                  
                    break;
                }
            }
        }
        return $result;
    }
    // Обновление курса валют
    public function updateCurrency() {
        $val = Zend_Registry::get('db')->fetchAll("SELECT * FROM currency WHERE flag!='UAH'");
        foreach ($val as $key => $value) {
            $tmp = CustomControllerAction::addCurrency($value['flag']);
            $cur = $tmp->rate / $tmp->size;
            Zend_Registry::get('db')->query("UPDATE currency SET value='$cur' WHERE flag='$value[flag]'");
        }
    }
    // функция перевода цены в определенную валюту
    public function currency($price, $from, $to) {
        if (!$to)
            $to = 1;
        $val1 = Zend_Registry::get('db')->fetchOne("SELECT value FROM currency WHERE id='$from' ");
        $val2 = Zend_Registry::get('db')->fetchOne("SELECT value FROM currency WHERE id='$to' ");
        //CustomControllerAction::pre($val1);
        $tmp = $price * $val1;
        $tmp = $tmp / $val2;
        return round($tmp,2);
    }

    public function cleanPostData($data) {
        $data = strip_tags($data);
        $data = strtolower($data);
        $data = preg_replace('~[^a-z0-9 \x80-\xFF]~i', "", $data);
        return $data;
    }

    public function cleanArrayToSearch($words = array(), $max = 0, $min_length) {
        $result = array();
        $i = 0;
        foreach ($words as $key => $value) {
            if (strlen(trim($value)) >= $min_length) {
                $i++;
                if ($i <= $max) {
                    $result[] = trim($value);
                }
            }
        }
        return $result;
    }

    public function getResultsSearch($words) {
        $sql = "SELECT * FROM (`content`) WHERE ";
        $i = 0;
        foreach ($words as $key => $value) {
            $i++;
            $sql = $sql . " `page_name` LIKE '%" . $value . "%' OR `page_text` LIKE '%" . $value . "%'" . ($i == count($words) ? "" : " OR");
        }
        $sql .= " ORDER BY `page_views` DESC";
        /* $result = mysql_query($sql);
          while($row = @mysql_fetch_object($result)){
          $return = $row;
          } */
        return $sql;
    }

    public function getMatchesSearch($content, $word = array()) {
        $matches = array();
        foreach ($content as $p) {
            $res[$p->getId()] = $p;
            foreach ($word as $w) {
                if (trim($w) != "") {
                    $w = trim($w);
                    $matches[$p->getId()] = $matches[$p->getId()] + count(explode($w, $p->name));
                    $matches[$p->getId()] = $matches[$p->getId()] + count(explode($w, $p->color));
                }
            }
        }
        arsort($matches);
        $i = 0;
        foreach ($matches as $k => $v) {
            $result[$i] = $res[$k];
            $result[$i]->matches = $v;
            $i++;
        }
        return $result;
    }
    // получение популярных ключевых слов и материалов
    public function getCountTags($content, $word = array()) {
        foreach ($word as $k => $v) {
            $key = array_keys($content, $v);
            $result[$v] = count($key);
        }
        arsort($result);
        if (count($result) > 30)
            $result = array_slice($result, 30);
        return $result;
    }
    /// функцию построения пагинатора
    public function Pag($count_pages, $active) {
        /* Входные параметры */
        $count_show_pages = 10;

        if ($count_pages > 1) { // Всё это только если количество страниц больше 1
                $left = $active - 1;
            $right = $count_pages - $active;
            if ($left < floor($count_show_pages / 2))
                $start = 1;
            else
                $start = $active - floor($count_show_pages / 2);
            $end = $start + $count_show_pages;
            if ($end > $count_pages) {
                $start -= ($end - $count_pages);
                $end = $count_pages;
                if ($start < 1)
                    $start = 1;
            }
            $pag->count_pages = $count_pages;
            $pag->active = $active;
            $pag->start = $start;
            $pag->end = $end + 1;
            //print_r($pag);
           return $pag;
        }
    }
    public function sendSMS($text,$phone){
        $sUrl  = 'http://letsads.com/api';
      /*  $sXML  = '<?xml version="1.0" encoding="UTF-8"?>
        <request>
            <auth>
                <login>380993805151</login>
                <password>VvV1985VvV</password>
            </auth>
            <balance />
        </request>';*/

        $sXML = '<?xml version="1.0" encoding="UTF-8"?>
                <request>
                    <auth>
                       <login>380993805151</login>
                       <password>VvV1985VvV</password>
                    </auth>
                    <message>
                        <from>dabahm.com</from>
                        <text>'.$text.'</text>
                        <recipient>'.$phone.'</recipient>
                    </message>
                </request>';
        $rCurl = curl_init($sUrl);
        curl_setopt($rCurl, CURLOPT_HEADER, 0);
        curl_setopt($rCurl, CURLOPT_POSTFIELDS, $sXML);
        curl_setopt($rCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($rCurl, CURLOPT_POST, 1);
        $sAnswer = curl_exec($rCurl);
        curl_close($rCurl);
        $dd = simplexml_load_string($sAnswer);
       if ($dd->name=='Complete') return true;
       if ($dd->name=='Error') return false;
       // CustomControllerAction::pre($dd);
    }
}

?>
